﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using UnityScriptEngine;
using StoreClientModule;

namespace MBBStoreClient
{
    public partial class frmChargedInvoiceEntry : Form
    {
        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();

        List<string> itemCode = new List<string>();
        DataTable items = new DataTable();
        DataTable accountName = new DataTable();
        DataTable prods = new DataTable();
        DataTable salesman = new DataTable();

        string curPO = "", curPOStamp = "", curItemCode = "", curSeries = "";
        string wrnEntMsg = "";
        float gtotal = 0f;
        string refNumber = "";

        bool qtyErr = false, prcErr = false, itmErr = false, trmErr = false,
            cmtErr = false, supErr = false, Committing = false,
            isViewing = false, anotherSeries=false;

        string contactNumber = "";

        //AutoChecker
        Timer tmr = new Timer();
        public frmChargedInvoiceEntry(string PONumber)
        {
            curPO = PONumber;
            isViewing = true;
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        public frmChargedInvoiceEntry()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
            
        }
        private void InitializeForm()
        {
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            txtUnit.SelectedIndex = 0;
            //Start AutoCheck timer
            if (!isViewing)
            {
                
                InitLookUp();
                txtAccountName.TextChanged += new EventHandler(txtSupplierName_TextChanged);
                txtCode.TextChanged += new EventHandler(txtCode_TextChanged);
                txtQty.TextChanged += new EventHandler(CheckValue);
                txtPrice.TextChanged += new EventHandler(CheckValue);
                btnAdd.Click += new EventHandler(btnAdd_Click);
                btnCommit.Click += new EventHandler(btnCommit_Click);
                btnAdd.LostFocus += new EventHandler(delegate(object sender, EventArgs e)
                {
                    txtQty.Focus();
                });
                mnuRemoveEntry.Click += new EventHandler(mnuRemoveEntry_Click);
               
                t.MethodCompleted += new EventHandler(t_MethodCompleted);
                txtTerms.Text = "30";
                txtInterest.Text = "0";
            }
            else
            {
               
                btnPayments.Click += new EventHandler(btnPayments_Click);
                btnPrint.Click += new EventHandler(btnPrint_Click);
                States(false);
                grpEntry.Visible = false;
                LoadData();
            }
            States(false);
            InitializeItemTable();
        }

        void btnPrint_Click(object sender, EventArgs e)
        {
            PrintPO();
        }
        void btnPayments_Click(object sender, EventArgs e)
        {
            frmChargedPaymentsEntry frm = new frmChargedPaymentsEntry(txtChargeInvoice.Text, txtRefNum.Text);
            frm.ShowDialog();
        }
        void mnuRemoveEntry_Click(object sender, EventArgs e)
        {
            if (grdItems.SelectedRows.Count == 0) return;
            DialogResult dlg = MessageBox.Show("The entry will be permanently deleted from the list.\r\n" +
                "Do you wish to continue?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            int sel = grdItems.SelectedRows[0].Index;
            items.Rows[sel].Delete();
            t.MethodCall(CheckEntry);
        }
        void btnCommit_Click(object sender, EventArgs e)
        {
            if (txtChargeInvoice.Text != "")
            {
                DialogResult dlg = MessageBox.Show("Please double check your entries before committing.\r\n" +
                    "Do you wish to continue saving?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlg == System.Windows.Forms.DialogResult.No) return;

                Committing = true;
                States(false);
                t.MethodCall(CheckChargedInvoice);
            }
            else
            {
                MessageBox.Show("Please Check your Entries.", "Commit", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        void btnAdd_Click(object sender, EventArgs e)
        {
            DataRow dr = items.NewRow();
            dr["Description"] = txtCode.Text;
            dr["Unit"] = txtUnit.Text;
            dr["Qty"] = float.Parse(txtQty.Text);
            dr["Amount"] = float.Parse(txtPrice.Text);
            
            items.Rows.Add(dr);

            grdItems.FirstDisplayedScrollingRowIndex = grdItems.Rows.Count - 1;
            DataRow[] drc = prods.Select("fDescription='" + txtCode.Text + "'");
            if (drc.Length == 1)
            {
                itemCode.Add(drc[0]["fBarcode"].ToString());
            }
            txtQty.Text = "";
            txtCode.Text = "";
            txtPrice.Text = "";
            txtQty.Focus();
            t.MethodCall(CheckEntry);
        }
        void txtCode_TextChanged(object sender, EventArgs e)
        {
            DataRow[] dr = prods.Select("fDescription='" + txtCode.Text + "'");
            if (dr.Length == 1)
            {
                itmErr = false;
                txtPrice.Text = dr[0]["fPCode"].ToString();
                txtCode.ForeColor = Color.Black;
                txtPrice.ForeColor = Color.Black;
            }
            else if (txtCode.Text.Length > 0)
            {
                itmErr = true;
                txtCode.ForeColor = Color.Red;
                txtPrice.ForeColor = Color.Red;
            }
            else
            {
                itmErr = false;
                txtCode.ForeColor = Color.Black;
                txtPrice.ForeColor = Color.Black;
            }
            t.MethodCall(CheckEntry);
        }
        void txtSupplierName_TextChanged(object sender, EventArgs e)
        {
            
            DataRow[] dr = accountName.Select("fSoldTo='" + txtAccountName.Text + "'");
            if (dr.Length == 2)
            {
                txtRefNum.Text = dr[1]["fRef"].ToString();
                txtAddress.Text = dr[0]["fAddress"].ToString();
                contactNumber = dr[0]["fTelNo"].ToString();

                txtAccountName.ForeColor = Color.Black;
                txtRefNum.ForeColor = Color.Black;
                txtAddress.ForeColor = Color.Black;
                
                txtRefNum.ReadOnly = true;
                txtAddress.ReadOnly = true;

                lblWarning.Text = "";
                supErr = false;
            }
            else 
            {
                if (!supErr)
                {
                    txtRefNum.Text = "N/A";
                    txtAddress.Text = "N/A";

                    txtAccountName.ForeColor = Color.Red;
                    txtRefNum.ForeColor = Color.Red;
                    txtAddress.ForeColor = Color.Red;

                    txtRefNum.ReadOnly = false;
                    txtAddress.ReadOnly = false;

                    lblWarning.Text = "Warning: Account Name not found in the database.";
                    supErr = true;
                }
            }
            t.MethodCall(CheckEntry);
            
        }
        void CheckValue(object sender, EventArgs e)
        {
            t.MethodCall(CheckEntry);
        }

        //Process Ended
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                
                MessageBox.Show(desc);
                States(true);
                switch (id)
                {
                    case "COMMIT":
                        Committing = false;
                        break;
                }
                tmr.Enabled = true;
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "INITGEN":
                        t.MethodCall(LoadData);
                        break;
                    case "GENERATE":
                    case "INIT":
                        proc.DBPUX_Data_Fetch(out dat);
                        
                        accountName = dat[0].ToDataTable();
                        if (!txtAccountName.Focused)
                        {
                            txtAccountName.AutoCompleteCustomSource.AddRange(dat[0].ToList<string>(1));
                        }
                        prods = dat[1].ToDataTable();
                        if (!txtCode.Focused)
                        {
                            txtCode.AutoCompleteCustomSource.AddRange(dat[1].ToList<string>(1));
                        }
                        salesman = dat[2].ToDataTable();
                        if (!txtSalesman.Focused)
                        {
                            txtSalesman.AutoCompleteCustomSource.AddRange(dat[2].ToList<string>(0));
                        }
                        break;
                    case "CHECKDUPLICATE":
                        proc.DBPUX_Data_Fetch(out dat);
                        if (dat[0].Data_Count == 0)
                        {
                            t.MethodCall(CommitPO);
                        }
                        else
                        {
                            MessageBox.Show("Duplicate Charged Invoice.", "Commit", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            States(true);
                            txtChargeInvoice.Text = "";
                            txtChargeInvoice.Focus();
                        }
                        break;
                    case "COMMIT":
                        
                        items.Clear();
                        txtChargeInvoice.Text = "";
                        txtAccountName.Text = "";
                        txtAddress.Text = "";
                        txtInterest.Text = "0";
                        txtTerms.Text = "30";
                        txtTotal.Text = "";
                        txtPO.Text = "";
                        txtSalesman.Text = "";
                        txtRefNum.Text = "";
                        contactNumber = "";

                        States(true);
                        MessageBox.Show("Charged Invoice "+txtChargeInvoice.Text +"Recorded", "Commit", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtChargeInvoice.Focus();
                        //btnClose_Click(null, null);
                        break;
                    case "LOAD":
                        proc.DBPUX_Data_Fetch(out dat);
                        
                        UnityElement e0, e1, e2;
                        dat[0].Data_Get(0, out e0);
                        dat[2].Data_Get(0, out e2);
                        txtChargeInvoice.Text = e0.Data_GetField(8).ToString();
                        txtPO.Text = e0.Data_GetField(6).ToString();
                        refNumber = e0.Data_GetField(5).ToString();

                       
                        txtSalesman.Text = e0.Data_GetField(4).ToString();
                        txtDate.Text = e0.Data_GetField(10).ToString();
                        txtInterest.Text = e2.Data_GetField(2).ToString();
                        txtTerms.Text = e2.Data_GetField(3).ToString();
                        
                        for (int i = 0; i < dat[1].Data_Count; i++)
                        {
                            DataRow dr = items.NewRow();

                            dat[1].Data_Get(i, out e1);
                            
                            dr["Description"] = e1.Data_GetField(3).ToString();
                            dr["Qty"] = e1.Data_GetField(1).ToString();
                            dr["Unit"] = e1.Data_GetField(2).ToString();
                            dr["Price"] = e1.Data_GetField(4).ToString();
                            double amt = double.Parse(e1.Data_GetField(1).ToString()) * double.Parse(e1.Data_GetField(4).ToString());
                            dr["Amount"] = amt.ToString();

                            items.Rows.Add(dr);
                        }
                        //Compute for the total
                        gtotal = 0;
                        for (int i = 0; i < items.Rows.Count; i++)
                        {
                            gtotal += (float)items.Rows[i]["Amount"];
                        }
                        txtTotal.Text = gtotal.ToString("#,#0.00");

                        LoadProfile();
                        
                        break;
                    case "LOADPROFILE":
                        proc.DBPUX_Data_Fetch(out dat);
                        UnityElement e3;
                        dat[0].Data_Get(0, out e3);
                        txtAccountName.Text = e3.Data_GetField(1).ToString();
                        txtRefNum.Text = e3.Data_GetField(0).ToString();
                        txtAddress.Text = e3.Data_GetField(2).ToString();
                        grdItems.Enabled = true;
                        grpDetails.Enabled = false;
                        btnPayments.Visible = true;
                        btnPrint.Visible = true;
                        lblWarningEntry.Text = "Loaded @ " + proc.ProcEnd() + " sec.";
                        break;

                };
                if (Committing || isViewing) return;
                tmr.Enabled = true;
                States(true);
            });
        }
        void t_MethodCompleted(object sender, EventArgs e)
        {
            t.SafeCall(this, delegate
            {
                switch(sender.ToString())
                {
                    case "CheckEntry":
                        lblWarningEntry.Text = wrnEntMsg;
                        if (qtyErr)
                            txtQty.ForeColor = Color.Red;
                        else
                            txtQty.ForeColor = Color.Black;

                        if (prcErr)
                            txtPrice.ForeColor = Color.Red;
                        else
                            txtPrice.ForeColor = Color.Black;

                        if (trmErr)
                            txtTerms.ForeColor = Color.Red;
                        else
                            txtTerms.ForeColor = Color.Black;

                        if (!qtyErr && !prcErr && !itmErr)
                            btnAdd.Visible = true;
                        else
                            btnAdd.Visible = false;

                        txtTotal.Text = gtotal.ToString("#,#0.00");
                        btnCommit.Visible = !cmtErr;
                        break;
                    case "CheckContent":
                        btnCommit.Visible = !cmtErr;
                        break;
                }
                if (Committing) return;
                tmr.Enabled = true;
            });
        }

        //Operations
        void InitGen()
        {
            while (proc.IsRunning)
            {
                System.Threading.Thread.Sleep(1);
            }
            UnityScript u = new UnityScript("INITGEN", 5);
            u.Script_Add(Script.DBPUX_INSERT, "tblpurchaseordergenerate (fCurNum, fCurSeries)", new string[] { "0", "C" });
            u.Script_Add(Script.DBPUX_INSERT, "tblpurchaseordergenerate (fCurNum, fCurSeries)", new string[] { "0", "" });
            proc.Run(u);
        }
        void LoadData()
        {
            while (proc.IsRunning)
            {
                System.Threading.Thread.Sleep(1);
            }
            proc.ProcStart();
            UnityScript u = new UnityScript("LOAD", 10);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT * FROM tblsalesdetail WHERE fInvoice ='{0}'",curPO));
            u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT * FROM tblsalesitem WHERE fInvoice ='{0}'", curPO));
            u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT * FROM tblchargebalance WHERE fInvoice ='{0}' AND fStatus = '1'", curPO));
            //u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT * FROM tblprofile WHERE fRef = " +
            //     "(SELECT fRef FROM tblsalesdetail WHERE fInvoice='{0}')", curPO));
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void LoadProfile()
        {
            
            UnityScript x = new UnityScript("LOADPROFILE", 10);
            x.Script_Add(Script.DBPUX_BEGIN);
            x.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT * FROM tblprofile WHERE fRef ='{0}'", refNumber));
            x.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(x);
        }
        void InitializeItemTable()
        {
            items.Columns.Add("Num");
            items.Columns.Add("Description");
            items.Columns.Add("Qty");
            items.Columns.Add("Unit");
            items.Columns.Add("Price");
            items.Columns.Add("Amount");

            items.Columns[0].AutoIncrementSeed = 1;
            items.Columns[0].AutoIncrement = true;
            items.Columns[0].DataType = typeof(int);

            items.Columns[2].DataType = typeof(float);
            items.Columns[2].DefaultValue = 0.00f;
            
            items.Columns[4].DataType = typeof(float);
            items.Columns[4].Expression = "[Amount] / [Qty]";
            
            items.Columns[5].DataType = typeof(float);
            items.Columns[5].DefaultValue = 0.00f;

            grdItems.DataSource = items;
            //grdItems.RowsDefaultCellStyle.WrapMode = DataGridViewTriState.True;

            grdItems.Columns[1].DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            grdItems.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grdItems.Columns[2].DefaultCellStyle.Format = "#,#0.00";
            grdItems.Columns[3].DefaultCellStyle.Format = "#,#0.00";
            grdItems.Columns[4].DefaultCellStyle.Format = "#,#0.00";
            grdItems.Columns[5].DefaultCellStyle.Format = "#,#0.00";

            grdItems.Columns[0].Width = (grdItems.Width * 7) / 100;
            grdItems.Columns[1].Width = (grdItems.Width * 43) / 100;
            grdItems.Columns[2].Width = (grdItems.Width * 13) / 100;
            grdItems.Columns[3].Width = (grdItems.Width * 8) / 100;
            grdItems.Columns[4].Width = (grdItems.Width * 14) / 100;
            grdItems.Columns[5].Width = (grdItems.Width * 14) / 100;
        }
        void InitLookUp()
        {
            while (proc.IsRunning)
            {
                System.Threading.Thread.Sleep(1);
            }
            UnityScript u = new UnityScript("INIT", 4);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblProfile");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fBarcode, fDescription, fPCode, fStamp FROM tblproducts");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT DISTINCT fSalesman FROM tblSalesDetail");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void CheckEntry()
        {
            float fqty = 0f, fprice = 0f, fterm = 0f;
            string qty = txtQty.Text, price = txtPrice.Text, terms = txtTerms.Text;
            //Check if Commit is valid
            if (txtAccountName.Text.Length != 0 && items.Rows.Count != 0 && !trmErr)
            {
                cmtErr = false;
            }
            else 
            {
                cmtErr = true;
            }
            //Check Qty
            if (!float.TryParse(qty, out fqty))
            {
                qtyErr = true;
                wrnEntMsg = "Invalid QUANTITY value detected!\r\n";
            }
            else
            {
                qtyErr = false;
                wrnEntMsg = "";
            }
            //Check Price
            if (!float.TryParse(price, out fprice))
            {
                prcErr = true;
                wrnEntMsg += "Invalid PRICE value detected!\r\n";
            }
            else
            {
                prcErr = false;
                if(!qtyErr) wrnEntMsg = "";
            }
            //Check Item
            if (itmErr)
            {
                wrnEntMsg += "ITEM NAME not found!\r\n";
            }
            else
            {
                if (!qtyErr && !prcErr) wrnEntMsg = "";
            }
            //Check Terms
            if (!float.TryParse(terms, out fterm))
            {
                trmErr = true;
                wrnEntMsg += "Invalid PAYMENT TERMS value detected!\r\n";
            }
            else
            {
                trmErr = false;
                if (!qtyErr && !prcErr && !itmErr) wrnEntMsg = "";
            }
            //Compute for the total
            gtotal = 0;
            for (int i = 0; i < items.Rows.Count; i++)
            {
                gtotal += (float)items.Rows[i]["Amount"];
            }
        }
        void CheckChargedInvoice()
        {
            UnityScript u = new UnityScript("CHECKDUPLICATE", 10);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblSalesDetail WHERE fInvoice = '" + txtChargeInvoice.Text + "'");
            u.Script_Add(Script.DBPUX_COMMIT);
            //Wait if UnityCall is in progress.
            System.Threading.Thread.Sleep(10);
            while (proc.IsRunning)
            {

            }
            proc.Run(u);
        }
        void CommitPO()
        {
            
            //Construct Charged Details.
            UnityScript u = new UnityScript("COMMIT", 10);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_INSERT, "tblSalesDetail(fStoreID, fSoldTo, fAddress, fTelNo, fSalesman, fRef, fPO, fInvoice, fInvoiceType, fDate )",
                new string[]{
                    Common.lStoreID,
                    txtAccountName.Text,
                    txtAddress.Text,
                    contactNumber,
                    txtSalesman.Text,
                    txtRefNum.Text,
                    txtPO.Text,
                    txtChargeInvoice.Text,
                    "Charged",
                    txtDate.Text,
                });
            //Construct Charged Items.
            for (int i = 0; i < items.Rows.Count; i++)
            {
                u.Script_Add(Script.DBPUX_INSERT, "tblSalesItem(fInvoice, fQty, fUnit, fUnitPrice, fDescription)",
                    new string[]{
                        txtChargeInvoice.Text,
                        items.Rows[i]["Qty"].ToString(),
                        items.Rows[i]["Unit"].ToString(),
                        items.Rows[i]["Price"].ToString(),
                        items.Rows[i]["Description"].ToString()
                    });
            }
            //Construct Charged Balance
            DateTime pDate = DateTime.Parse(txtDate.Text);
            double days = double.Parse(txtTerms.Text);
            string due = pDate.AddDays(days).ToShortDateString();
            
            u.Script_Add(Script.DBPUX_INSERT, "tblChargeBalance(fInvoice, fBalance, fPercentage, fTerms, fDueDates, fDate, fStatus)",
                new string[]{
                    txtChargeInvoice.Text,
                    float.Parse(txtTotal.Text).ToString(),
                    txtInterest.Text,
                    txtTerms.Text,
                    due,
                    txtDate.Text,
                    "1"
                });
            
            u.Script_Add(Script.DBPUX_COMMIT);
            //Wait if UnityCall is in progress.
            System.Threading.Thread.Sleep(10);
            while (proc.IsRunning)
            {

            }
            proc.Run(u);
        }
        void States(bool s)
        {
            grpDetails.Enabled = s;
            grpEntry.Enabled = s;
            grdItems.Enabled = s;
        }

        //Printing Module
        void PrintPO()
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                ppdlg.ShowDialog();
            }
        }
        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.PageBounds.Left + 50;
            float lw = e.PageBounds.Width - 50;
            float th = e.PageBounds.Height - 100;
            float tHt = 0;
            Font cFont;
            StringFormat sf = new StringFormat();
            //Title
            cFont = new Font("Arial", 16f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            y = 50;
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString("MBB ROYALE INT'L INC.", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            cFont = new Font("Arial", 8f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("MacArthur Hi-way, Guinhawa, Malolos Bulacan", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            cFont = new Font("Arial", 8f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("Telephone Number: (044) 791-03-78 , (044) 662-40-79", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            cFont = new Font("Arial", 8f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            //e.Graphics.DrawString("Fax Number: (044) 662-37-62", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //Line
            y += tHt;
            y += tHt;
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            e.Graphics.DrawString("PURCHASE ORDER FORM", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            y += tHt;
            y += tHt;
            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y), new PointF(lw, y));
            //SUPPLIER Line
            y += tHt;
            y += tHt;
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("REFERENCE NO: ", cFont, Brushes.Black, lm + 20, y, new StringFormat());
            e.Graphics.DrawString("P.O. NO: ", cFont, Brushes.Black, lw - 280, y, new StringFormat());

            cFont = new Font("Arial", 12f, FontStyle.Italic);
            e.Graphics.DrawString("" + txtRefNum.Text, cFont, Brushes.Black, lm + 180, y, new StringFormat());
            e.Graphics.DrawString("" + txtChargeInvoice.Text, cFont, Brushes.Black, 600, y, new StringFormat());

            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 180, y), new PointF(500, y));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(760, y), new PointF(600, y));
            //SUPPLIER Line
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("SUPPLIER NAME: ", cFont, Brushes.Black, lm + 20, y, new StringFormat());
            e.Graphics.DrawString("DATE: ", cFont, Brushes.Black, lw - 280, y, new StringFormat());

            cFont = new Font("Arial", 12f, FontStyle.Italic);
            e.Graphics.DrawString("" + txtAccountName.Text, cFont, Brushes.Black, lm + 180, y, new StringFormat());
            e.Graphics.DrawString("" + txtDate.Text, cFont, Brushes.Black, 600, y, new StringFormat());

            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 180, y), new PointF(500, y));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(760, y), new PointF(600, y));
            //ADDRESS Line

            cFont = new Font("Arial", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("ADDRESS: ", cFont, Brushes.Black, lm + 20, y, new StringFormat());
            cFont = new Font("Arial", 12f, FontStyle.Italic);
            e.Graphics.DrawString("" + txtAddress.Text, cFont, Brushes.Black, lm + 180, y, new StringFormat());

            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 180, y), new PointF(760, y));

            y += tHt;
            //Table Columns
            cFont = new Font("Arial", 11f, FontStyle.Bold);
            y += tHt;
            e.Graphics.DrawString("No.", cFont, Brushes.Black, lm + 4, y, new StringFormat());
            e.Graphics.DrawString("Description", cFont, Brushes.Black, lm + 40, y, new StringFormat());
            e.Graphics.DrawString("Qty", cFont, Brushes.Black, lm + 405, y, new StringFormat());
            e.Graphics.DrawString("Price", cFont, Brushes.Black, lm + 565, y, new StringFormat());
            e.Graphics.DrawString("Sub Total", cFont, Brushes.Black, lm + 660, y, new StringFormat());

            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (tHt / 2)), new PointF(lw, y - (tHt / 2)));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y + tHt), new PointF(lw, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (tHt / 2)), new PointF(lm, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lw, y - (tHt / 2)), new PointF(lw, y + tHt));

            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 35, y - (tHt / 2)), new PointF(lm + 35, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 400, y - (tHt / 2)), new PointF(lm + 400, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 560, y - (tHt / 2)), new PointF(lm + 560, y + tHt));
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 655, y - (tHt / 2)), new PointF(lm + 655, y + tHt));

            //Table
            y += (tHt * 1.25f);
            cFont = new Font("Arial Narrow", 10f, FontStyle.Regular);
            tHt = cFont.GetHeight(e.Graphics);
            bool nf = false;
            for (int i = 0; i < 30; i++)
            {
                e.Graphics.DrawString((i + 1) + "", cFont, Brushes.Black, lm + 4, y, new StringFormat());
                if (grdItems.Rows.Count > i)
                {
                    e.Graphics.DrawString("" + grdItems.Rows[i].Cells[1].Value.ToString(), cFont, Brushes.Black, lm + 40, y, new StringFormat());
                    e.Graphics.DrawString("" + grdItems.Rows[i].Cells[2].Value.ToString(), cFont, Brushes.Black, lm + 405, y, new StringFormat());
                    e.Graphics.DrawString("" + grdItems.Rows[i].Cells[3].Value.ToString(), cFont, Brushes.Black, lm + 565, y, new StringFormat());
                    e.Graphics.DrawString("" + grdItems.Rows[i].Cells[4].Value.ToString(), cFont, Brushes.Black, lm + 660, y, new StringFormat());
                }
                else
                {
                    if (!nf)
                    {
                        //Nothing Follows
                        e.Graphics.DrawString("******************** Nothing Follows ********************", cFont, Brushes.Black, lm + 300, y, new StringFormat());
                        nf = true;
                    }
                }
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y + tHt), new PointF(lw, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (tHt / 2)), new PointF(lm, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lw, y - (tHt / 2)), new PointF(lw, y + tHt));

                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 35, y - (tHt / 2)), new PointF(lm + 35, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 400, y - (tHt / 2)), new PointF(lm + 400, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 560, y - (tHt / 2)), new PointF(lm + 560, y + tHt));
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 655, y - (tHt / 2)), new PointF(lm + 655, y + tHt));

                y += (tHt * 1.25f);

            }

            //STORE Line
            y += tHt;
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("NUMBER OF ITEMS: " + grdItems.Rows.Count, cFont, Brushes.Black, lm + 20, y, new StringFormat());
            y += tHt;
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("SHIP TO: ", cFont, Brushes.Black, lm + 20, y, new StringFormat());
            cFont = new Font("Arial", 11f, FontStyle.Italic);
            e.Graphics.DrawString("" + StoreClientModule.Common.lStoreName, cFont, Brushes.Black, lm + 180, y, new StringFormat());
            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 180, y), new PointF(500, y));
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            e.Graphics.DrawString("ADDRESS: ", cFont, Brushes.Black, lm + 20, y, new StringFormat());
            cFont = new Font("Arial", 11f, FontStyle.Italic);
            e.Graphics.DrawString("" + StoreClientModule.Common.lStoreAddress, cFont, Brushes.Black, lm + 180, y, new StringFormat());
            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm + 180, y), new PointF(760, y));

            y += tHt;
            e.Graphics.DrawString("_____________________________", cFont, Brushes.Black, lw - 190, y, sf);

            y += tHt;
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("AUTHORIZED SIGNATURE", cFont, Brushes.Black, lw - 190, y, sf);

        }
    }
    //Code Log:
    //- Speed up entry checking by removing the method call from the timer.
    //- Removed the CheckContent method as the CheckEntry method is sufficient for checking
    //  user inputs.
}